package com.gree.elasticsearch.security.provider;

import com.gree.elasticsearch.security.JwtAuthenticationToken;
import com.gree.elasticsearch.security.JwtService;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.security.SignatureException;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/30
 */
@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    private Logger logger = LoggerFactory.getLogger(JwtAuthenticationProvider.class.getName());

    @Autowired
    private JwtService jwtService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = authentication.getCredentials().toString();
        try {
            jwtService.verifyJwt(token);
            logger.debug("jwt authentication success");
            Authentication latestAuthentication = jwtService.getAuthentication(token);
            return latestAuthentication;
        } catch (JwtException e) {
            throw e;
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        logger.debug("current authentication method is {}", aClass.getName());
        return aClass.isAssignableFrom(JwtAuthenticationToken.class);
    }
}
